﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.IO;

namespace KeyboardImageViewer
{
    /// <summary>
    /// Interaction logic for Import.xaml
    /// </summary>
    public partial class Import : Window
    {
        public Import(MainWindow window)
        {
            this.Owner = window;

            InitializeComponent();

            ImageManager.Config.ApplyWindowSize("Import", this);

            if (ImageManager.Config.DeleteDuplicatesOnImport)
            {
                this.deleteDuplicatesBox.IsChecked = true;
            }

            if (!ImageManager.Config.TrackDuplicates)
            {
                this.deleteDuplicatesBox.IsEnabled = false;
            }

            List<string> configRules = ImageManager.Config.ImportRules;

            for (int i = 0; i < configRules.Count; i++)
            {
                this.importRules.Text += configRules[i];

                if (i != configRules.Count - 1)
                {
                    this.importRules.Text += Environment.NewLine;
                }
            }

            this.importRules.SelectionStart = 0;
            this.importRules.SelectionLength = 0;

            this.UpdatePreviewList();
        }

        private void UpdatePreviewList()
        {
            List<Regex> importRegList = this.ImportRegList;

            ObservableCollection<RenameFileInfo> renameFiles = new ObservableCollection<RenameFileInfo>();

            foreach (int imageId in ImageListControl.ImageList)
            {
                ImageUserData imageData = Database.GetImageUserData(ImageManager.Connection, imageId);

                string oldName = Path.GetFileName(imageData.Name);
                string newName = "";
                string newTags = "";

                bool imageToBeDeleted = false;
                if (ImageManager.Config.TrackDuplicates && (bool)this.deleteDuplicatesBox.IsChecked)
                {
                    List<int> exactDuplicates = DuplicateUtils.FindExactDuplicates(ImageManager.Connection, imageId);

                    foreach (int duplicateImageId in exactDuplicates)
                    {
                        if (!ImageListControl.ImageList.Contains(duplicateImageId))
                        {
                            imageToBeDeleted = true;
                            newName = "(Deleting)";
                            break;
                        }
                    }
                }

                if (!imageToBeDeleted)
                {
                    foreach (Regex importRule in importRegList)
                    {
                        Match m = importRule.Match(oldName);

                        if (m.Success)
                        {
                            if (m.Groups["filename"].Value != "")
                            {
                                newName = m.Groups["filename"].Value;
                            }
                            else
                            {
                                newName = oldName;
                            }

                            if (m.Groups["artist"].Value != "")
                            {
                                newTags = m.Groups["artist"].Value;
                            }

                            break;
                        }
                    }
                }

                renameFiles.Add(new RenameFileInfo { OldName = oldName, NewName = newName, NewTags = newTags, WillBeDeleted = imageToBeDeleted });
            }

            this.previewList.ItemsSource = renameFiles;

            this.ResizeGridViewColumn(this.newNameColumn);
            this.ResizeGridViewColumn(this.newTagsColumn);
        }

        private void ResizeGridViewColumn(GridViewColumn column)
        {
            if (double.IsNaN(column.Width))
            {
                column.Width = column.ActualWidth;
            }

            column.Width = double.NaN;
        }

        private List<Regex> ImportRegList
        {
            get
            {
                List<Regex> importRegList = new List<Regex>();

                string[] rules = this.importRules.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string rule in rules)
                {
                    string trimRule = rule.Trim();

                    if (trimRule != "")
                    {
                        try
                        {
                            importRegList.Add(new Regex(trimRule));
                        }
                        catch (ArgumentException e)
                        {
                            MessageBox.Show("Invalid rule:\n" + trimRule + "\nWill not be applied:\n\n" + e.Message);
                        }
                    }
                }

                return importRegList;
            }
        }

        public class RenameFileInfo
        {
            public string OldName { get; set; }
            public string NewName { get; set; }
            public string NewTags { get; set; }
            public bool WillBeDeleted { get; set; }
            public string DeletingString { get; set; }
        }

        private void refreshPreview_Click(object sender, RoutedEventArgs e)
        {
            this.UpdatePreviewList();
        }

        private void importButton_Click(object sender, RoutedEventArgs e)
        {
            EditOperations.CleanVisibleItems(this.ImportRegList, ImageManager.Config.TrackDuplicates && (bool)this.deleteDuplicatesBox.IsChecked);

            this.UpdatePreviewList();
        }

        private void deleteDuplicatesBox_Checked(object sender, RoutedEventArgs e)
        {
            this.UpdatePreviewList();
        }

        private void deleteDuplicatesBox_Unchecked(object sender, RoutedEventArgs e)
        {
            this.UpdatePreviewList();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            string[] rules = this.importRules.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            List<string> newRules = new List<string>();

            foreach (string rule in rules)
            {
                string trimRule = rule.Trim();

                if (trimRule != "")
                {
                    newRules.Add(trimRule);
                }
            }

            ImageManager.Config.ImportRules = newRules;

            ImageManager.Config.SaveWindowSize("Import", this);

            ImageManager.Config.DeleteDuplicatesOnImport = (bool)this.deleteDuplicatesBox.IsChecked;
        }
    }
}
